const blogModel = require("../models/blogsModel");

// 创建博客
const createBlogPost = async (req, res) => {
  const { title, content, summary, category_id, status } = req.body;
  console.log(req.body);
  console.log(req.file);

  // -- 前端传入字段 title,content,summary,cover_image,category_id,status
  // -- 后端处理字段 user_id,created_at,updated_at

  // 👇 multer 会把上传的文件挂在 req.file 上
  const cover_image = req.file ? `/uploads/blogs/${req.file.filename}` : null;

  try {
    const result = await blogModel.createPost(
      title,
      content,
      summary,
      cover_image,
      category_id,
      status,
      req.user.userId
    );
    res.status(200).json({ code: 0, msg: "创建成功", data: result });
  } catch (error) {
    console.error("❌ 创建失败:", error);
    res.status(500).json({ code: 500, msg: "创建失败" });
  }
};

// 列表
const getBlogList = async (req, res) => {
  const { pageNum = 1, pageSize = 10 } = req.query;
  try {
    const result = await blogModel.getBlogList(pageNum, pageSize);
    res.status(200).json({ code: 0, msg: "获取成功", data: result });
  } catch (error) {
    console.error("❌ 获取失败:", error);
  }
};

// 点赞和取消点赞
// 通过req.status 10:点赞,20:取消点赞
const likeBlog = async (req, res) => {
  console.log(req.body);
  try {
    const result = await blogModel.likeBlog(req.body.id, req.body.status);
    res.status(200).json({ code: 0, msg: "操作成功", data: result });
  } catch (error) {
    console.error("❌ 操作失败:", error);
  }
};

module.exports = {
  createBlogPost,
  getBlogList,
  likeBlog,
};
